<?php

namespace app\api\model;

use app\api\model\Common;
use think\Validate;
use think\Db;

class SceenModel extends Common
{
    //
    protected $name = 'sceen_model';

    public function detail()
    {
        return $this->hasOne('SceenDetail', 'mid')->field('config,mid');
    }
    /**
     * 
     */
    public function getList($condition, $keyword, $page, $limit)
    {
        try {
            $map = [
                'status' => 1
            ];
            if ($condition) {
                $map[$condition] = ['like', '%' . trim($keyword) . '%'];
            }
            $result = $this->with('detail')->where($map)->limit($limit)->page($page)->order('id desc')->select();
            $total =  $this->where($map)->count();
            foreach ($result as &$value) {
                $status = [0 => '禁用', 1 => '启用'];
                $value['statusDetail'] = $status[$value['status']];
                $value['config'] = json_decode($value['detail']['config'], true) ? json_decode($value['detail']['config'], true) : '';
                unset($value['detail']);
            }
            return [
                'list' => $result,
                'total' => $total,
                'totalPage' => $limit != 0 ? ceil($total / $limit) : 0
            ];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    public function editDefaultModel($id)
    {
        $viewData = $this->get($id);
        if (!$viewData) {
            $this->error = '暂无此数据';
            return false;
        }
        if($viewData->default_view == 1)
        {
            return true;
        }
        try{
            Db::startTrans();
            //修改默认模板
            $_bef = $this->get(['default_view' => 1]);
            $_bef->default_view = 0;
            $_bef->update_time = time();
            $_bef->save();
            $viewData->default_view = 1;
            $viewData->update_time = time();
            $viewData->save();
            Db::commit();
            return true;
        }catch(\Exception $e)
        {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
}
